package Cau12;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class mahoaImpl extends UnicastRemoteObject implements Imahoa {
	private FileInputStream inFromHardDisk;
	private FileOutputStream fos;
	private static final long serialVersionUID = 1L;
	private String namefile = "temp.txt";
	byte[] arrByteOfSentFile=null;

	public mahoaImpl() throws RemoteException {
		super();
	}

	@Override
	public byte[] XuLyFile(byte[] data) throws RemoteException {
		// TODO Auto-generated method stub
		try {

			fos = new FileOutputStream(namefile);
			fos.write(data);
			fos.flush();
			fos.close();
			// //
			File file = new File(namefile);

			String contents = "";
			BufferedReader reader = null;

			reader = new BufferedReader(new FileReader(file));
			String text = "";

			// repeat until all lines is read
			while ((text = reader.readLine()) != null) {
				contents = stringConv(text);
				SaveFile(contents);
			}
			reader.close();
			//gui lai mang byte file
			inFromHardDisk = new FileInputStream("temp1.txt");
			int size = inFromHardDisk.available();
			arrByteOfSentFile = new byte[size];
			inFromHardDisk.read(arrByteOfSentFile, 0, size);
			inFromHardDisk.close();
			file.delete();
			File de=new File("temp1.txt");
			de.delete();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arrByteOfSentFile;
	}

	public String stringConv(String s) {
		String temp = "";
		String[] ds;
		ds = s.split(" ");
		for (int i = ds.length - 1; i >= 0; i--) {
			temp += ds[i] + " ";
		}
		return temp;
	}

	public void SaveFile(String s) throws IOException {
		try {
			FileOutputStream os = new FileOutputStream("temp1.txt", true);
			PrintWriter pr = new PrintWriter(os);
			pr.println(s);
			pr.close();
			os.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
